package cn.ug.product.service.impl;

import cn.ug.account.bean.DataDictionaryBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.Config;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.ProductTypeEnum;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.*;
import cn.ug.info.bean.ArticleBean;
import cn.ug.mall.bean.EntityGoldBean;
import cn.ug.pay.bean.status.TradeStatus;
import cn.ug.product.bean.GoldPriceRecordBean;
import cn.ug.product.bean.request.ProductAuditParamBean;
import cn.ug.product.bean.request.ProductDiscountBean;
import cn.ug.product.bean.request.ProductParamBean;
import cn.ug.product.bean.response.*;
import cn.ug.product.bean.response.ProductInfo;
import cn.ug.product.bean.status.CommonConstants;
import cn.ug.product.mapper.*;
import cn.ug.product.mapper.entity.*;
import cn.ug.product.service.*;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.DateUtils;
import cn.ug.util.UF;
import com.alibaba.fastjson.JSONObject;
import com.gexin.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ywl
 * @date 2018/1/12 0012
 */
@Service
public class ProductServiceImpl extends BaseServiceImpl implements ProductService {
    private static Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);
    @Autowired
    private ArticleService articleService;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Autowired
    private ProductTradeTimeService productTradeTimeService;

    @Resource
    private ProductInfoService productInfoService;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductTradeTimeMapper productTradeTimeMapper;

    @Resource
    private TradeTemplateTimeMapper tradeTemplateTimeMapper;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private DozerBeanMapper dozerBeanMapper;
    @Autowired
    private AmqpTemplate amqpTemplate;
    @Resource
    private Config config;

    @Autowired
    private ProductImgService productImgService;

    @Autowired
    private ProductLeaseInfoService productLeaseInfoService;

    @Resource
    private RateSettingsService rateSettingsService;

    @Resource
    private GoldPriceRecordService goldPriceRecordService;

    @Resource
    private LabelService labelService;

    @Resource
    private ProcessTemplateService processTemplateService;

    @Resource
    private ProductPublicityMapper productPublicityMapper;

    @Resource
    private ProductDiscountSettingsMapper productDiscountSettingsMapper;

    @Resource
    private ProductMemberInviteRecordMapper productMemberInviteRecordMapper;

    @Resource
    private ProductMemberSubtractMapper productMemberSubtractMapper;

    @Override
    public DataTable<ProductManageBean> query(ProductParamBean productParamBean) {
        com.github.pagehelper.Page<ProductParamBean> pages = PageHelper.startPage(productParamBean.getPageNum(), productParamBean.getPageSize());
        productParamBean.setName(UF.escapeSql(productParamBean.getName()));
        List<ProductManageBean> dataList = productMapper.queryProductList(productParamBean);
        //计算募集剩余克数、百分比
        if (dataList != null && !dataList.isEmpty()) {
            for (ProductManageBean bean : dataList) {
                if (bean.getRaiseGram().compareTo(BigDecimal.ZERO) == 0) {
                    bean.setRaisedPer(BigDecimal.ZERO);
                    bean.setSurplusGram(BigDecimal.ZERO);
                } else {
                    bean.setSurplusGram(bean.getRaiseGram().subtract(bean.getToRaiseGram()));
                    BigDecimal per = BigDecimal.ZERO;
                    if (!bean.getToRaiseGram().equals(BigDecimal.ZERO) && !bean.getRaiseGram().equals(BigDecimal.ZERO)) {
                        per = bean.getToRaiseGram().divide(bean.getRaiseGram(), 4, BigDecimal.ROUND_HALF_UP);
                    }
                    if (per.equals(BigDecimal.ZERO)) {
                        bean.setRaisedPer(BigDecimal.ZERO);
                    } else {
                        bean.setRaisedPer(per.multiply(BigDecimal.valueOf(100l)).setScale(2));
                    }
                }
                if (ProductTypeEnum.EXPERIENCE_GOLD.getType() == bean.getType()) {
                    List<ProductLeaseInfoBean> productLeaseInfoBeanList = productLeaseInfoService.findList(bean.getId());
                    if (!CollectionUtils.isEmpty(productLeaseInfoBeanList)) {
                        ProductLeaseInfoBean productLeaseInfoBean = productLeaseInfoBeanList.get(0);
                        LeaseDay leaseDay = new LeaseDay();
                        BeanUtils.copyProperties(productLeaseInfoBean, leaseDay);
                        bean.setLeaseDay(leaseDay);
                    }
                }
            }
        }
        return new DataTable<>(productParamBean.getPageNum(), productParamBean.getPageSize(), pages.getTotal(), dataList);
    }

    @Transactional
    @Override
    public int save(ProductBean entityBean) {
        //验证
        Ensure.that(entityBean.getName()).isNull("15000002");
        Ensure.that(entityBean.getType()).isNull("15000003");
        Ensure.that(entityBean.getUpTimeString()).isNull("15000004");
        Ensure.that(entityBean.getEffectiveDay()).isNull("15000005");
        Ensure.that(entityBean.getYearsIncome()).isNull("15000006");
        Ensure.that(entityBean.getInvestDay()).isNull("15000007");
        Ensure.that(entityBean.getInterestAccrualType()).isNull("15000008");
        Ensure.that(entityBean.getInterestAccrualDay()).isNull("15000009");
        //Ensure.that(entityBean.getRiskType()).isNull("15000010");
        Ensure.that(entityBean.getSettlementType()).isNull("15000011");
        Ensure.that(entityBean.getSettingPriceType()).isNull("15000012");
        if (entityBean.getSettingPriceType() == 2) {
            Ensure.that(entityBean.getSettingPrice()).isNull("15000013");
        }
        //Ensure.that(entityBean.getRepaymentWay()).isNull("15000018");
        Ensure.that(entityBean.getDetail()).isNull("15000019");
        Ensure.that(entityBean.getLabel()).isNull("15000020");
        Ensure.that(entityBean.getIncomeLabel()).isNull("15000021");
        Ensure.that(entityBean.getInsurance()).isNull("15000022");
        Ensure.that(entityBean.getProtocolId()).isNull("15000023");
        Ensure.that(entityBean.getList() == null || entityBean.getList().isEmpty()).isTrue("15000028");

        //设置默认值
        if (StringUtils.isBlank(entityBean.getPriceMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getPriceMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        //过滤标签字符串
        entityBean.setLabel(handle(entityBean.getLabel()));
        entityBean.setIncomeLabel(handle(entityBean.getIncomeLabel()));

        //作废老产品
        cancelProduct(entityBean.getId());

        LoginBean loginBean = LoginHelper.getLoginBean();
        entityBean.setId(UF.getRandomUUID());
        entityBean.setCreateUserId(loginBean.getId());  //设置创建用户id
        entityBean.setCreateUser(loginBean.getName());  //设置创建用户姓名
        Product product = dozerBeanMapper.map(entityBean, Product.class);
        product.setUpTime(UF.getDate(entityBean.getUpTimeString()));
        if (product.getIsActivity() == null) {
            product.setIsActivity(2);
        }
        product.setStopTime(getStopTime(entityBean.getUpTimeString(), Integer.valueOf(entityBean.getEffectiveDay())));  //设置停售时间
        productMapper.insert(product);

        //新增时间交易受限
        productTradeTimeService.save(product.getId(), entityBean.getList());

        //新增产品详情
        productInfoService.save(product.getId(), entityBean.getProductInfoList());
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int productSave(ProductBean entityBean) {
        Ensure.that(StringUtils.isBlank(entityBean.getName())).isTrue("15000002");
        Ensure.that(entityBean.getType()).isNull("15000003");
        Ensure.that(entityBean.getUpTimeString()).isNull("15000004");
        Ensure.that(entityBean.getHeading()).isNull("15000077");
        Ensure.that(entityBean.getHeading().length() > 15).isTrue("15000079");
        Ensure.that((StringUtils.isNotBlank(entityBean.getHeadingNotes()) && entityBean.getHeadingNotes().length() > 7)).isTrue("15000078");
        //Ensure.that(entityBean.getSubhead() == null).isTrue("15000037");
        Ensure.that((entityBean.getSubhead() != null && entityBean.getSubhead().length > 3)).isTrue("15000044");
        if (entityBean.getSubhead() != null && entityBean.getSubhead().length > 0) {
            int length = entityBean.getSubhead().length;
            for (int i=0;i<length;i++) {
                Ensure.that(entityBean.getSubhead()[i].length() > 5).isTrue("15000080");
            }
        }

        Ensure.that(entityBean.getSettingPriceType()).isNull("15000012");
        if (entityBean.getSettingPriceType() == 2) {
            Ensure.that(entityBean.getSettingPrice()).isNull("15000013");
        }
        //协议
        Ensure.that(entityBean.getProtocolId()).isNull("15000023");
        //货号
        Ensure.that(entityBean.getEntityItemno()).isNull("15000052");
        //产品规格
        Ensure.that(entityBean.getSpecification() == null).isTrue("15000035");

        //作废老产品
        cancelProduct(entityBean.getId());

        LoginBean loginBean = LoginHelper.getLoginBean();
        entityBean.setId(UF.getRandomUUID());
        entityBean.setCreateUserId(loginBean.getId());  //设置创建用户id
        entityBean.setCreateUser(loginBean.getName());  //设置创建用户姓名

        int status = 0;
        switch (entityBean.getType()) {
            case 8:
                status = smoothSave(entityBean);
                break;
            case 9:
                status = discountSave(entityBean);
                break;
            default:
                status = entitySave(entityBean);
                break;
        }

        return status;
    }

    /**
     * 折扣金发布
     *
     * @param entityBean
     * @return
     */
    public int discountSave(ProductBean entityBean) {
        checkDiscountParams(entityBean);
        entityBean.setInterestAccrualDay(1);
        String productId = saveProductDB(entityBean);
        ProductDiscountBean productDiscountBean = entityBean.getDiscountBean();
        //设置折扣金立减信息
        ProductDiscountSettings productDiscountSettings = new ProductDiscountSettings();
        BeanUtils.copyProperties(productDiscountBean, productDiscountSettings);
        productDiscountSettings.setProductId(productId);
        int rows = productDiscountSettingsMapper.insertSelective(productDiscountSettings);
        Ensure.that(rows).isLt(1, "00000005");
        return 0;
    }

    /**
     * 安稳金发布
     *
     * @param entityBean
     * @return
     */
    public int smoothSave(ProductBean entityBean) {
        checkSmoothParams(entityBean);
        String productId = saveProductDB(entityBean);

        if (!CollectionUtils.isEmpty(entityBean.getProductPublicityBeans())) {
            /**
             * 新增产品宣传信息
             */
            for (ProductPublicityBean productPublicityBean : entityBean.getProductPublicityBeans()) {
                productPublicityBean.setProductId(productId);
            }
            int rows = productPublicityMapper.insert(entityBean.getProductPublicityBeans());
            Ensure.that(rows).isLt(1, "00000005");
        }
        return 0;
    }

    /**
     * 实物金产品发布
     */
    public int entitySave(ProductBean entityBean) {
        Ensure.that(entityBean.getCanBuyUserType()).isNull("15000056");
        if (ProductTypeEnum.ENTITY.getType() == entityBean.getType()) {
            Ensure.that(entityBean.getEffectiveDay()).isNull("15000005");
            Ensure.that(entityBean.getInterestAccrualType()).isNull("15000008");
            Ensure.that(entityBean.getLabel()).isNull("15000020");
            Ensure.that(entityBean.getProtocolId()).isNull("15000023");
            /**************************************2018-11-29 修改--开始**************************************************************/
            Ensure.that(entityBean.getAwardSetting() == null).isTrue("15000050");
            Ensure.that(entityBean.getLeaseProtocolId() == null).isTrue("15000051");
            Ensure.that(entityBean.getEntityItemno()).isNull("15000052");

            Ensure.that(entityBean.getSpecification() == null).isTrue("15000035");
            Ensure.that(entityBean.getMarketPrice()).isNull("15000036");
            Ensure.that(entityBean.getUserAstrictStatus()).isNull("15000055");
            Ensure.that(entityBean.getStock()).isNull("15000057");
            Ensure.that(entityBean.getProcessId()).isNull("15000058");
            Ensure.that(entityBean.getUserAstrictStatus() == 1 &&
                    (entityBean.getUserAstrictNum() == null || entityBean.getUserAstrictNum() == 0)).isTrue("15000045");
            Ensure.that(entityBean.getUserAstrictStatus() == 2 &&
                    (entityBean.getUserAstrictGram() == null || entityBean.getUserAstrictGram() == 0)).isTrue("15000049");

            //Ensure.that(entityBean.getHeadImgList() == null || entityBean.getHeadImgList().isEmpty()).isTrue("15000038");
            Ensure.that(entityBean.getImgDetails() == null).isTrue("15000039");
            Ensure.that(entityBean.getProductInfoList() == null || entityBean.getProductInfoList().isEmpty()).isTrue("15000040");
            Ensure.that(entityBean.getProductInfoList().size() < 2).isTrue("15000042");
            Ensure.that(entityBean.getProductInfoList().size() > 6).isTrue("15000041");
            Ensure.that(entityBean.getLeaseDayList() == null || entityBean.getLeaseDayList().isEmpty()).isTrue("15000061");

            entityBean.getProductInfoList().stream().forEach(productInfoBean -> {
                Ensure.that(CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())).isTrue("15000048");
                Ensure.that(StringUtils.isBlank(productInfoBean.getTitle())).isTrue("15000047");
                Ensure.that(productInfoBean.getProductIntroduceList().size() < 1).isTrue("15000043");
                Ensure.that(productInfoBean.getProductIntroduceList().size() > 10).isTrue("15000041");
            });
            SerializeObject serializeObject = rateSettingsService.get(RateKeyEnum.ENTITY_GOLD.getKey());
            if (serializeObject != null && serializeObject.getData() != null) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(serializeObject.getData());
                EntityGoldBean entityGoldBean = JSONObject.toJavaObject(jsonObject, EntityGoldBean.class);
                entityBean.setLeaseCloseType(entityGoldBean.getLeaseCloseType());
                entityBean.setLeaseCalculateGoldType(entityGoldBean.getLeaseCalculateGoldType());
                entityBean.setLeaseCalculateGoldTime(entityGoldBean.getLeaseCalculateGoldTime());
            }
            //设置最低的购买克重
            entityBean.setGramMin(new BigDecimal(entityBean.getSpecification()));
            //设置库存克重
            entityBean.setRaiseGram(new BigDecimal(entityBean.getStock().intValue() * entityBean.getSpecification().intValue()));
            //设置默认值
            entityBean.setYearsIncome(BigDecimal.ZERO);
        } else if (ProductTypeEnum.EXPERIENCE_GOLD.getType() == entityBean.getType()) {
            SerializeObject serializeObject = rateSettingsService.get(RateKeyEnum.EXPERIENCE_GOLD.getKey());
            if (serializeObject != null && serializeObject.getData() != null) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(serializeObject.getData());
                entityBean.setLeaseCloseType(jsonObject.getIntValue("closeType"));
            }
            entityBean.setInterestAccrualType(2);
            entityBean.setRaiseGram(new BigDecimal(0));
            entityBean.setYearsIncome(entityBean.getLeaseDayList().get(0).getYearsIncome());
        }


        /*********************************结束***********************************************/
        //设置开始计息日期 T+1
        entityBean.setInterestAccrualDay(1);
        entityBean.setInvestDay("0");
        if (StringUtils.isBlank(entityBean.getPriceMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getPriceMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        //过滤标签字符串
        entityBean.setLabel(handle(entityBean.getLabel()));
        entityBean.setIncomeLabel(handle(entityBean.getIncomeLabel()));

        Product product = dozerBeanMapper.map(entityBean, Product.class);
        product.setSubhead(StringUtils.join(entityBean.getSubhead(), ","));
        product.setUpTime(UF.getDate(entityBean.getUpTimeString()));
        if (product.getIsActivity() == null) {
            product.setIsActivity(2);
        }

        if (ProductTypeEnum.EXPERIENCE_GOLD.getType() == entityBean.getType()) {
            product.setEffectiveDay("0");
            DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonConstants.FORMAT);
            LocalDateTime currentTime = LocalDateTime.parse(entityBean.getUpTimeString(), df);
            product.setStopTime(currentTime.plusYears(1));
        } else {
            product.setStopTime(getStopTime(entityBean.getUpTimeString(), Integer.valueOf(entityBean.getEffectiveDay())));  //设置停售时间
        }
        productMapper.insert(product);

        //新增产品详情
        productInfoService.save(product.getId(), entityBean.getProductInfoList());

        //新增产品图片信息
        if (ProductTypeEnum.ENTITY.getType() == entityBean.getType()) {
            productImgService.save(product.getId(), 2, Arrays.asList(entityBean.getImgDetails()));
        }

        //新增产品回租期限
        List<ProductLeaseInfoBean> productLeaseInfoBeans = new ArrayList<>();
        List<LeaseDay> leaseDays = entityBean.getLeaseDayList().stream().sorted((a, b) -> a.getLeaseDay() - b.getLeaseDay()).collect(Collectors.toList());
        for (LeaseDay leaseDay : leaseDays) {
            ProductLeaseInfoBean productLeaseInfoBean = new ProductLeaseInfoBean();
            productLeaseInfoBean.setLeaseDay(leaseDay.getLeaseDay());
            productLeaseInfoBean.setYearsIncome(leaseDay.getYearsIncome());
            productLeaseInfoBean.setProductId(product.getId());
            productLeaseInfoBeans.add(productLeaseInfoBean);
        }
        productLeaseInfoService.save(productLeaseInfoBeans);
        return 0;
    }

    /**
     * 产品数据落地公共方法
     *
     * @param entityBean
     * @return 产品id
     */
    private String saveProductDB(ProductBean entityBean) {
        Product product = dozerBeanMapper.map(entityBean, Product.class);
        product.setSubhead(StringUtils.join(entityBean.getSubhead(), ","));
        product.setUpTime(UF.getDate(entityBean.getUpTimeString()));
        if (product.getIsActivity() == null) {
            product.setIsActivity(2);
        }
        product.setStopTime(getStopTime(entityBean.getUpTimeString(), Integer.valueOf(entityBean.getEffectiveDay())));  //设置停售时间
        //产品新增
        int rows = productMapper.insert(product);
        Ensure.that(rows).isLt(1, "00000005");

        //新增产品详情
        rows = productInfoService.save(product.getId(), entityBean.getProductInfoList());
        Ensure.that(rows).isLt(1, "00000005");
        //新增产品回租期限
        List<ProductLeaseInfoBean> productLeaseInfoBeans = new ArrayList<>();
        List<LeaseDay> leaseDays = entityBean.getLeaseDayList().stream().sorted((a, b) -> a.getLeaseDay() - b.getLeaseDay()).collect(Collectors.toList());
        for (LeaseDay leaseDay : leaseDays) {
            ProductLeaseInfoBean productLeaseInfoBean = new ProductLeaseInfoBean();
            productLeaseInfoBean.setLeaseDay(leaseDay.getLeaseDay());
            productLeaseInfoBean.setYearsIncome(leaseDay.getYearsIncome());
            productLeaseInfoBean.setProductId(product.getId());
            productLeaseInfoBeans.add(productLeaseInfoBean);
        }
        rows = productLeaseInfoService.save(productLeaseInfoBeans);
        Ensure.that(rows).isLt(1, "00000005");
        return product.getId();
    }

    @Override
    public int productUpdate(ProductBean entityBean) {
        Product product = productMapper.findById(entityBean.getId());
        if (product != null) {
            Ensure.that(entityBean.getImg() == null).isTrue("15000038");
            Ensure.that(entityBean.getImgDetails() == null).isTrue("15000039");

            Ensure.that(entityBean.getProductInfoList() == null || entityBean.getProductInfoList().isEmpty()).isTrue("15000040");
            if (ProductTypeEnum.SMOOTH_GOLD.getType() != product.getType()) {
                Ensure.that(entityBean.getProductInfoList().size() < 2).isTrue("15000042");
                Ensure.that(entityBean.getProductInfoList().size() > 6).isTrue("15000041");
            }
            entityBean.getProductInfoList().stream().forEach(productInfoBean -> {
                Ensure.that(CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())).isTrue("15000048");
                Ensure.that(StringUtils.isBlank(productInfoBean.getTitle())).isTrue("15000047");
                Ensure.that(productInfoBean.getProductIntroduceList().size() < 1).isTrue("15000043");
                Ensure.that(productInfoBean.getProductIntroduceList().size() > 10).isTrue("15000041");
            });

            /**
             * 产品宣传图片
             */
            if (ProductTypeEnum.SMOOTH_GOLD.getType() == product.getType() && !CollectionUtils.isEmpty(entityBean.getProductPublicityBeans())) {
                Ensure.that(entityBean.getProductPublicityBeans().size() > 5).isTrue("15000064");
                entityBean.getProductPublicityBeans().stream().forEach(productPublicityBean -> {
                    Ensure.that(StringUtils.isBlank(productPublicityBean.getTitle())).isTrue("15000065");
                    Ensure.that(StringUtils.isBlank(productPublicityBean.getContent())).isTrue("15000066");
                    Ensure.that(StringUtils.isBlank(productPublicityBean.getImgUrl())).isTrue("15000067");
                    Ensure.that(productPublicityBean.getTitle().length() > 15).isTrue("15000068");
                    Ensure.that(productPublicityBean.getContent().length() > 300).isTrue("15000069");
                });
            }

            Map imgMap = new HashMap();
            imgMap.put("img", entityBean.getImg());
            imgMap.put("id", entityBean.getId());
            productMapper.updateImgById(imgMap);
            if (ProductTypeEnum.SMOOTH_GOLD.getType() == product.getType()) {
                if (!CollectionUtils.isEmpty(entityBean.getProductPublicityBeans())) {
                    //产品宣传信息
                    productPublicityMapper.deleteById(entityBean.getId());
                    for (ProductPublicityBean productPublicityBean : entityBean.getProductPublicityBeans()) {
                        productPublicityBean.setProductId(product.getId());
                    }
                    int rows = productPublicityMapper.insert(entityBean.getProductPublicityBeans());
                    Ensure.that(rows).isLt(1, "00000005");
                }
            } else if (ProductTypeEnum.DISCOUNT_GOLD.getType() == product.getType()) {
                ProductDiscountBean productDiscountBean = entityBean.getDiscountBean();
                Ensure.that(productDiscountBean.getMaxNum() == null || productDiscountBean.getMaxNum() < 0
                        || productDiscountBean.getMaxNum() > 10).isTrue("15000071");

                //设置折扣金立减信息
                ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(entityBean.getId());
                if (productDiscountBean.getMaxNum() < productDiscountSettings.getMaxNum()) {
                    Ensure.that(0).isLt(1, "15000076");
                }

                if (productDiscountSettings != null) {
                    productDiscountSettings.setMaxNum(productDiscountBean.getMaxNum());
                    int rows = productDiscountSettingsMapper.updateByProductId(productDiscountSettings);
                    Ensure.that(rows).isLt(1, "00000005");
                }
            } else {
                //新增详情图片 先删除之前的
                productImgService.delete(entityBean.getId());
                int rows = productImgService.save(product.getId(), 2, Arrays.asList(entityBean.getImgDetails()));
                Ensure.that(rows).isLt(1, "00000005");
            }
            //新增产品详情  先删除
            productInfoService.delete(entityBean.getId());
            int rows = productInfoService.save(product.getId(), entityBean.getProductInfoList());
            Ensure.that(rows).isLt(1, "00000005");
        }
        return 0;
    }

    @Override
    public ProductFindBean queryProductById(String id) {
        ProductFindBean productFindBean = productMapper.queryProductById(id);

        //设置产品协议
        if (ProductTypeEnum.EXPERIENCE_GOLD.getType() != productFindBean.getType()) {
            try {
                SerializeObject<ArticleBean> o = articleService.find("", productFindBean.getProtocolId());
                if (o.getCode() == ResultType.NORMAL) {
                    ArticleBean articleBean = o.getData();
                    productFindBean.setProtocolName(articleBean.getTitle());
                }
            } catch (Exception e) {
                return productFindBean;
            }

            //设置实物金回租协议
            if (StringUtils.isNotBlank(productFindBean.getLeaseProtocolId())) {
                try {
                    SerializeObject<ArticleBean> o = articleService.find("", productFindBean.getLeaseProtocolId());
                    if (o.getCode() == ResultType.NORMAL) {
                        ArticleBean articleBean = o.getData();
                        productFindBean.setLeaseProtocolName(articleBean.getTitle());
                    }
                } catch (Exception e) {
                    return productFindBean;
                }
            }

            if (productFindBean.getType() != ProductTypeEnum.ENTITY.getType()) {
                SerializeObject<DataDictionaryBean> db1 = null;
                try {
                    //设置还款方式
                    db1 = dataDictionaryService.queryDataDictionary(CommonConstants.REPAYMENT_WAY, productFindBean.getRepaymentWay());
                    if (db1.getCode() == ResultType.NORMAL) {
                        DataDictionaryBean entity = db1.getData();
                        productFindBean.setRepaymentWayName(entity.getItemName());

                    }
                } catch (Exception e) {
                    return productFindBean;
                }

                try {
                    //设置成标方式
                    db1 = dataDictionaryService.queryDataDictionary(CommonConstants.STANDARD_WAY, productFindBean.getStandardWay());
                    if (db1.getCode() == ResultType.NORMAL) {
                        DataDictionaryBean entity = db1.getData();
                        productFindBean.setStandardWayName(entity.getItemName());
                    }
                } catch (Exception e) {
                    return productFindBean;
                }
            }

            //设置产品明细
            List<ProductInfo> productInfoBeanList = productInfoMapper.findList(id);
            try {
                LinkedHashMap<String, List<ProductInfo>> groupBy = productInfoBeanList.stream().collect(Collectors.groupingBy(ProductInfo::getTitle, LinkedHashMap::new, Collectors.toList()));
                List<ProductInfoBean> productInfoBeans = new ArrayList<>();
                for (Map.Entry<String, List<ProductInfo>> entry : groupBy.entrySet()) {
                    ProductInfoBean productInfoBean = new ProductInfoBean();
                    productInfoBean.setTitle(entry.getKey());
                    productInfoBean.setProductIntroduceList(entry.getValue());
                    if (!CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())) {
                        Collections.sort(productInfoBean.getProductIntroduceList(), new Comparator<ProductInfo>() {
                            @Override
                            public int compare(ProductInfo o1, ProductInfo o2) {
                                if (o1.getSort() > o2.getSort()) {
                                    return 1;
                                }
                                return -1;
                            }
                        });
                    }
                    productInfoBeans.add(productInfoBean);
                }
                productFindBean.setProductInfoBeanNewList(productInfoBeans);
                //productFindBean.setProductInfoBeanList(productInfoBeanList);
            } catch (Exception e) {
                //老产品
                //productFindBean.setProductInfoBeanList(productInfoBeanList);
            }

            if (ProductTypeEnum.SMOOTH_GOLD.getType() == productFindBean.getType()) {
                List<ProductPublicityBean> productPublicityBeans = productPublicityMapper.findList(id);
                productFindBean.setProductPublicityBeans(productPublicityBeans);
            } else if (ProductTypeEnum.DISCOUNT_GOLD.getType() == productFindBean.getType()) {
                ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(id);
                if (!Objects.isNull(productDiscountSettings)) {
                    ProductDiscountBean productDiscountBean = new ProductDiscountBean();
                    BeanUtils.copyProperties(productDiscountSettings, productDiscountBean);
                    productFindBean.setDiscountBean(productDiscountBean);
                }
            } else {
                List<ProductImgBean> productImgBeanList = productImgService.findList(id);
                if (!CollectionUtils.isEmpty(productImgBeanList)) {
                    productFindBean.setImgDetails(productImgBeanList.stream().map(o -> o.getUrl()).collect(Collectors.toList()));
                }
            }
        }
        List<ProductLeaseInfoBean> productLeaseInfoBeanList = productLeaseInfoService.findList(id);
        if (!CollectionUtils.isEmpty(productLeaseInfoBeanList)) {
            List<LeaseDay> leaseDayList = new ArrayList<>();
            for (ProductLeaseInfoBean productLeaseInfoBean : productLeaseInfoBeanList) {
                LeaseDay leaseDay = new LeaseDay();
                BeanUtils.copyProperties(productLeaseInfoBean, leaseDay);
                leaseDayList.add(leaseDay);
            }
            productFindBean.setLeaseDayList(leaseDayList);
        }

        List<LabelBean> labelList = new ArrayList<>();
        //实物金产品设置标签实体
        if (productFindBean.getType() == ProductTypeEnum.ENTITY.getType()) {
            if (StringUtils.isNotBlank(productFindBean.getLabel())) {
                for (String labelId : productFindBean.getLabel().split(",")) {
                    SerializeObject serializeObject = labelService.findLabelById(Integer.valueOf(labelId));
                    LabelBean labelBean = JSON.parseObject(JSON.toJSONString(serializeObject.getData()), LabelBean.class);
                    labelList.add(labelBean);
                }
            }
        }
        productFindBean.setLabelList(labelList);
        return productFindBean;
    }

    @Override
    public ProductBean findById(String id) {
        Product product = productMapper.findById(id);
        if (product != null) {
            //ProductBean productBean = dozerBeanMapper.map(product, ProductBean.class);
            ProductBean productBean = new ProductBean();
            BeanUtils.copyProperties(product, ProductBean.class, new String[]{"subhead"});
            productBean.setUpTimeString(UF.getFormatDateTime(product.getUpTime()));
            productBean.setStopTimeString(UF.getFormatDateTime(product.getStopTime()));
            return productBean;
        }
        return null;
    }

    @Transactional
    @Override
    public SerializeObject updateAuditStatus(ProductAuditParamBean productAuditParamBean) {
        Product product = productMapper.findById(productAuditParamBean.getId());
        if (product != null && ProductTypeEnum.EXPERIENCE_GOLD.getType() == product.getType()
                && productAuditParamBean.getAuditStatus().intValue() == 2) {
            List<Product> result = productMapper.findExperience(ProductTypeEnum.EXPERIENCE_GOLD.getType());
            if (!CollectionUtils.isEmpty(result) && result.size() > 0) {
                return new SerializeObject(ResultType.ERROR, "15000063");
            }
        }

        if (product != null && ProductTypeEnum.DISCOUNT_GOLD.getType() == product.getType()
                && productAuditParamBean.getAuditStatus().intValue() == 2) {
            List<Product> result = productMapper.findExperience(ProductTypeEnum.DISCOUNT_GOLD.getType());
            if (!CollectionUtils.isEmpty(result) && result.size() > 0) {
                return new SerializeObject(ResultType.ERROR, "15000073");
            }
        }

        LoginBean loginBean = LoginHelper.getLoginBean();
        productAuditParamBean.setAuditUserId(loginBean.getId());
        productAuditParamBean.setAuditUser(loginBean.getName());
        int num = productMapper.updateAuditStatus(productAuditParamBean);
        //审核通过--产品上架
        if (CommonConstants.ProductAuditStatus.PASS_AUDIT.getIndex() == productAuditParamBean.getAuditStatus()) {
            String array[] = {productAuditParamBean.getId()};
            updateShelfState(array, CommonConstants.ProductShelfState.UP_SHELF.getIndex());
        }
        Ensure.that(num).isLt(1, "00000005");
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @Transactional
    @Override
    public int updateIsHot(String[] ids, int isHot) {
        boolean flag = false;
        boolean flag2 = false;
        for (String id : ids) {
            Product product = productMapper.findById(id);
            Ensure.that(ProductTypeEnum.DISCOUNT_GOLD.getType() == product.getType()).isTrue("15000074");
            if (product.getType() == 6) {
                flag = true;
            }

            if (product.getType() == 8) {
                flag2 = true;
            }
        }

        if ((!flag || !flag2) && isHot == 2 && ids.length > 1) {
            Ensure.that(0).isLt(1, "15000060");
        }

        List<ProductHotBean> isHotList = productMapper.queryIsHotList();
        if (!CollectionUtils.isEmpty(isHotList)) {
            if (ids.length > 1) {
                productMapper.updateIsHotList(isHotList.stream().map(o -> o.getId()).collect(Collectors.toList()));
            } else {
                Product product = productMapper.findById(ids[0]);
                if (product != null) {
                    List<ProductHotBean> overList = isHotList.stream().filter(o -> o.getType() == product.getType()).collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(overList)) {
                        productMapper.updateIsHotList(overList.stream().map(o -> o.getId()).collect(Collectors.toList()));
                    }
                }
            }

        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", ids);
        map.put("isHot", isHot);
        int num = productMapper.updateIsHot(map);
        return num;
    }

    @Transactional
    @Override
    public int updateShelfState(String[] id, int shelfState) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("shelfState", shelfState);
        int num = productMapper.updateShelfState(map);
        return num;
    }


    @Override
    public List<ProductBean> queryOnlineList(Integer type) {
        List<ProductBean> productBeans = new ArrayList<>();
        List<Product> result = productMapper.findExperience(type);
        if (!CollectionUtils.isEmpty(result)) {
            for (Product product : result) {
                ProductBean productBean = new ProductBean();
                BeanUtils.copyProperties(product, productBean);
                if (type == ProductTypeEnum.DISCOUNT_GOLD.getType()) {
                    ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(product.getId());
                    if (Objects.nonNull(productDiscountSettings)) {
                        ProductDiscountBean discountBean = new ProductDiscountBean();
                        productBean.setDiscountBean(discountBean);
                    }
                }
                productBeans.add(productBean);
            }
        }
        return productBeans;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveProductInviteRecord(String friendId, String memberId) {
        logger.info("折扣金邀请好友业务请求参数----" + friendId + "----memberId" + memberId);
        List<Product> result = productMapper.findExperience(ProductTypeEnum.DISCOUNT_GOLD.getType());
        if (!CollectionUtils.isEmpty(result)) {
            Product product = result.get(0);
            ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(product.getId());
            if (Objects.nonNull(productDiscountSettings)) {
                //判断是自主注册的还是邀请注册的
                if (StringUtils.isNotBlank(friendId)) {
                    Map memberSubtractFriendIdMap = new HashMap();
                    memberSubtractFriendIdMap.put("productId", productDiscountSettings.getProductId());
                    memberSubtractFriendIdMap.put("memberId", friendId);
                    ProductMemberSubtract memberSubtract = productMemberSubtractMapper.selectByProductIdAndFriendId(memberSubtractFriendIdMap);

                    //查询该邀请人在当前在售折扣金产品中的邀请好友记录数
                    Map pamams = new HashMap();
                    pamams.put("productId", productDiscountSettings.getProductId());
                    pamams.put("friendId", friendId);
                    int rows = productMemberInviteRecordMapper.countByProductIdAndFriendId(pamams);
                    if (productDiscountSettings.getRatio() * productDiscountSettings.getMaxNum() > rows) {
                        ProductMemberInviteRecord productMemberInviteRecord = new ProductMemberInviteRecord();
                        productMemberInviteRecord.setProductId(productDiscountSettings.getProductId());
                        productMemberInviteRecord.setFriendId(friendId);
                        productMemberInviteRecord.setMemberId(memberId);
                        int row = productMemberInviteRecordMapper.insertSelective(productMemberInviteRecord);
                        Ensure.that(row).isLt(1, "00000005");


                        if (memberSubtract != null) {
                            if ((rows + 1) % productDiscountSettings.getRatio().intValue() == 0 &&
                                    memberSubtract.getInviteNum().intValue() / productDiscountSettings.getRatio().intValue() < productDiscountSettings.getMaxNum()) {
                                memberSubtract.setNum(memberSubtract.getNum() + 1);
                            }
                            if (memberSubtract.getInviteNum().intValue() / productDiscountSettings.getRatio().intValue() < productDiscountSettings.getMaxNum()) {
                                memberSubtract.setInviteNum(memberSubtract.getInviteNum() + 1);
                            }
                            row = productMemberSubtractMapper.updateByPrimaryKeySelective(memberSubtract);
                            Ensure.that(row).isLt(1, "00000005");
                        } else {
                            //用户第一次邀请好友
                            //折扣金立减次数记录表
                            ProductMemberSubtract productMemberSubtract = new ProductMemberSubtract();
                            productMemberSubtract.setProductId(productDiscountSettings.getProductId());
                            productMemberSubtract.setMemberId(friendId);
                            productMemberSubtract.setNum(productDiscountSettings.getNewMemberNum());
                            productMemberSubtract.setInviteNum(0);
                            row = productMemberSubtractMapper.insertSelective(productMemberSubtract);
                            Ensure.that(row).isLt(1, "00000005");
                        }
                    }
                }

                Map memberSubtractMap = new HashMap();
                memberSubtractMap.put("productId", productDiscountSettings.getProductId());
                memberSubtractMap.put("memberId", memberId);
                ProductMemberSubtract productMemberSubtracts = productMemberSubtractMapper.selectByProductIdAndFriendId(memberSubtractMap);
                if (Objects.isNull(productMemberSubtracts)) {
                    //折扣金立减次数记录表
                    ProductMemberSubtract productMemberSubtract = new ProductMemberSubtract();
                    productMemberSubtract.setProductId(productDiscountSettings.getProductId());
                    productMemberSubtract.setMemberId(memberId);
                    productMemberSubtract.setNum(productDiscountSettings.getNewMemberNum());
                    productMemberSubtract.setInviteNum(0);
                    int row = productMemberSubtractMapper.insertSelective(productMemberSubtract);
                    Ensure.that(row).isLt(1, "00000005");
                }
            }
        }
        return 0;
    }


    @Override
    public ProductMemberInviteRecordRes queryProductInviteRecord(String memberId, String productId) {
        ProductMemberInviteRecordRes productMemberInviteRecordRes = new ProductMemberInviteRecordRes();
        Map pamams = new HashMap();
        pamams.put("productId", productId);
        pamams.put("friendId", memberId);
        List<ProductMemberInviteRecordBean> productMemberInviteRecordList = productMemberInviteRecordMapper.queryByProductIdAndFriendId(pamams);
        productMemberInviteRecordRes.setProductMemberInviteRecordList(productMemberInviteRecordList);
        ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(productId);
        if (productDiscountSettings != null) {
            if (!CollectionUtils.isEmpty(productMemberInviteRecordList)) {
                if (productMemberInviteRecordList.size() / productDiscountSettings.getRatio() < productDiscountSettings.getMaxNum()) {
                    productMemberInviteRecordRes.setLimitStatus(false);
                } else {
                    productMemberInviteRecordRes.setLimitStatus(true);
                }
            }
        }

        return productMemberInviteRecordRes;
    }

    @Override
    public ProductSubtractBean queryProductSubtractInfo(String memberId, String mobile, String productId) {
        Product product = productMapper.findById(productId);
        //判断是否是在售的折扣金
        if (ProductTypeEnum.DISCOUNT_GOLD.getType() == product.getType() && StringUtils.isNotBlank(memberId) && StringUtils.isNotBlank(mobile)) {
            Map<String, Object> param = new HashMap<>();
            param.put("userName", mobile);
            param.put("memberId", memberId);
            List<Integer> list = productMapper.queryTransactionNum(param);

            param.put("productId", productId);
            ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(productId);
            if (productDiscountSettings != null) {
                ProductMemberSubtract productMemberSubtract = productMemberSubtractMapper.selectByProductIdAndFriendId(param);
                if (list.get(0).intValue() > 0 || list.get(1).intValue() > 0) {
                    //老用户
                    if (productMemberSubtract == null) {
                        //折扣金立减次数记录表
                        productMemberSubtract = new ProductMemberSubtract();
                        productMemberSubtract.setProductId(productDiscountSettings.getProductId());
                        productMemberSubtract.setMemberId(memberId);
                        productMemberSubtract.setNum(productDiscountSettings.getOldMemberNum());
                        productMemberSubtract.setInviteNum(0);
                        int row = productMemberSubtractMapper.insertSelective(productMemberSubtract);
                        Ensure.that(row).isLt(1, "00000005");
                    }

                } else {
                    if (productMemberSubtract == null) {
                        //折扣金立减次数记录表
                        productMemberSubtract = new ProductMemberSubtract();
                        productMemberSubtract.setProductId(productDiscountSettings.getProductId());
                        productMemberSubtract.setMemberId(memberId);
                        productMemberSubtract.setNum(productDiscountSettings.getNewMemberNum());
                        productMemberSubtract.setInviteNum(0);
                        int row = productMemberSubtractMapper.insertSelective(productMemberSubtract);
                        Ensure.that(row).isLt(1, "00000005");
                    }
                }
            }
        }

        if (product != null) {
            Map pamams = new HashMap();
            pamams.put("productId", productId);
            pamams.put("memberId", memberId);
            ProductMemberSubtract memberSubtract = productMemberSubtractMapper.selectByProductIdAndFriendId(pamams);
            ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(productId);

            ProductSubtractBean productSubtractBean = new ProductSubtractBean();
            productSubtractBean.setMemberId(memberId);
            productSubtractBean.setNum(memberSubtract.getNum());
            productSubtractBean.setInviteNum(memberSubtract.getInviteNum());
            productSubtractBean.setMaxDiscountNum(productDiscountSettings.getMaxNum());
            productSubtractBean.setNewMemberNum(productDiscountSettings.getNewMemberNum());
            productSubtractBean.setOldMemberNum(productDiscountSettings.getOldMemberNum());
            productSubtractBean.setRatio(productDiscountSettings.getRatio());
            productSubtractBean.setMarketPrice(product.getMarketPrice().intValue());
            return productSubtractBean;
        }

        return null;
    }

    @Override
    public int memberSubtractNumUpdate(String memberId, String productId, Integer type) {
        Map pamams = new HashMap();
        pamams.put("productId", productId);
        pamams.put("memberId", memberId);
        ProductMemberSubtract memberSubtract = productMemberSubtractMapper.selectByProductIdAndFriendId(pamams);
        if (memberSubtract != null) {
            if (type == 1) {
                memberSubtract.setNum(memberSubtract.getNum() - 1);
            } else {
                memberSubtract.setNum(memberSubtract.getNum() + 1);
            }
            int row = productMemberSubtractMapper.updateByPrimaryKeySelective(memberSubtract);
            Ensure.that(row).isLt(1, "00000005");
            return 1;
        }
        return 0;
    }

    @Override
    public int updateIsOpen(String id, int isOpen) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("isOpen", isOpen);
        int num = productMapper.updateIsOpen(map);
        return num;
    }

    @Override
    public ProductHotBean queryNewMemberProduct() {
        ProductHotBean productHotBean = productMapper.queryNewMemberProduct();
        if (productHotBean != null && productHotBean.getRaiseGram() != null) {
            double toRaiseGram = productHotBean.getToRaiseGram() == null ? 0 : productHotBean.getToRaiseGram().doubleValue();
            double raiseGram = productHotBean.getRaiseGram().doubleValue();
            if (raiseGram > 0) {
                productHotBean.setPercent((int) (toRaiseGram * 100 / raiseGram));
            }
        }
        return productHotBean;
    }

    @Override
    public List<ProductHotBean> queryHotProductList(String appVsersion) {
        List<ProductHotBean> list = productMapper.queryHotProductList();
        boolean flag = false;
        if (cn.ug.util.StringUtils.compareVersion("3.4.4", appVsersion) > 0) {
            flag = true;
        }
        if (!CollectionUtils.isEmpty(list)) {
            for (ProductHotBean productHotBean : list) {
                if (productHotBean.getSettingPriceType() == 2) {
                    //金价类型设置(2:自定义价格)   市场价格= 自定义价格 + 产品参数设置的值
                    productHotBean.setMarketPrice(productHotBean.getMarketPrice() == null ? productHotBean.getSettingPrice() : productHotBean.getSettingPrice().add(productHotBean.getMarketPrice()));
                    //售价
                    productHotBean.setSellingPrice(productHotBean.getSettingPrice());
                } else {
                    GoldPriceRecordBean goldPriceRecordBean = goldPriceRecordService.findLastByTime();
                    if (goldPriceRecordBean != null) {
                        //金价类型设置(1:实时金价 )   市场价格= 实时金价 + 产品参数设置的值
                        productHotBean.setMarketPrice(productHotBean.getMarketPrice());
                        //售价
                        productHotBean.setSellingPrice(goldPriceRecordBean.getLatestpri());
                    }
                }

                //查询头图列表
                List<ProductImgBean> productImgBeanList = productImgService.findList(productHotBean.getId());
                if (!CollectionUtils.isEmpty(productImgBeanList)) {
                    productHotBean.setImgDetails(productImgBeanList.stream().map(o -> o.getUrl()).collect(Collectors.toList()));
                }
            }
        }
        if (flag) {
            //app版本小于3.4.4热销产品只返回实物金
            List<ProductHotBean> resultList = list.stream().filter(o -> o.getType() == 6).collect(Collectors.toList());
            return resultList;
        }
        //排序
        list.sort(Comparator.comparing(ProductHotBean::getType).reversed());
        return list;
    }

    @Override
    public List<ProductHotBean> queryProductList(Integer type) {
        List<ProductHotBean> dataList = productMapper.queryProductBaseList(type);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (ProductHotBean productHotBean : dataList) {
                if (productHotBean.getType() == ProductTypeEnum.EXPERIENCE_GOLD.getType()
                        || productHotBean.getType() == ProductTypeEnum.SMOOTH_GOLD.getType()) {
                    List<ProductLeaseInfoBean> productLeaseInfoBeanList = productLeaseInfoService.findList(productHotBean.getId());
                    if (!CollectionUtils.isEmpty(productLeaseInfoBeanList)) {
                        ProductLeaseInfoBean productLeaseInfoBean = productLeaseInfoBeanList.get(0);
                        LeaseDay leaseDay = new LeaseDay();
                        BeanUtils.copyProperties(productLeaseInfoBean, leaseDay);
                        productHotBean.setLeaseDay(leaseDay);
                    }


                }
                //查询头图列表
                List<ProductImgBean> productImgBeanList = productImgService.findList(productHotBean.getId());
                if (!CollectionUtils.isEmpty(productImgBeanList)) {
                    productHotBean.setImgDetails(productImgBeanList.stream().map(o -> o.getUrl()).collect(Collectors.toList()));
                }
            }
        }

        return dataList;
    }

    @Override
    public ProductDetailBean queryProductDetailById(String id) {
        Product product = productMapper.findById(id);
        if (product == null) {
            return null;
        }
        if (product.getShelfState() == 2) {
            return null;
        }
        ProductDetailBean productDetailBean = dozerBeanMapper.map(product, ProductDetailBean.class);
        //设置产品协议
        if (ProductTypeEnum.EXPERIENCE_GOLD.getType() != productDetailBean.getType()) {
            //设置产品协议
            SerializeObject<ArticleBean> o = articleService.find("", productDetailBean.getProtocolId());
            if (o.getCode() == ResultType.NORMAL) {
                ArticleBean articleBean = o.getData();
                productDetailBean.setProtocolName(articleBean.getTitle());
                productDetailBean.setProtocolContent(articleBean.getContent());
            }
            /**
             * 设置产品介绍页信息
             */
            //设置产品明细
            List<ProductInfo> productInfoBeanList = productInfoMapper.findList(id);
            try {
                LinkedHashMap<String, List<ProductInfo>> groupBy = productInfoBeanList.stream().collect(Collectors.groupingBy(ProductInfo::getTitle, LinkedHashMap::new, Collectors.toList()));
                List<ProductInfoBean> productInfoBeans = new ArrayList<>();
                for (Map.Entry<String, List<ProductInfo>> entry : groupBy.entrySet()) {
                    ProductInfoBean productInfoBean = new ProductInfoBean();
                    productInfoBean.setTitle(entry.getKey());
                    productInfoBean.setProductIntroduceList(entry.getValue());
                    if (!CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())) {
                        Collections.sort(productInfoBean.getProductIntroduceList(), new Comparator<ProductInfo>() {
                            @Override
                            public int compare(ProductInfo o1, ProductInfo o2) {
                                if (o1.getSort() > o2.getSort()) {
                                    return 1;
                                }
                                return -1;
                            }
                        });
                    }
                    productInfoBeans.add(productInfoBean);
                }
                productDetailBean.setProductInfoBeanNewList(productInfoBeans);
                // productDetailBean.setProductInfoBeanList(productInfoBeanList);
            } catch (Exception e) {
                //老产品
                //productDetailBean.setProductInfoBeanList(productInfoBeanList);
            }

            //查询产品详情图片
            List<ProductImgBean> productImgBeanList = productImgService.findList(id);
            if (!CollectionUtils.isEmpty(productImgBeanList)) {
                productDetailBean.setImgDetails(productImgBeanList.stream().map(a -> a.getUrl()).collect(Collectors.toList()));
            }
        }
        //设置售价和市场价
        if (product.getSettingPriceType() == 2) {
            //金价类型设置(2:自定义价格)   市场价格= 自定义价格 + 产品参数设置的值
            productDetailBean.setMarketPrice(productDetailBean.getMarketPrice() == null ? product.getSettingPrice() : product.getSettingPrice().add(productDetailBean.getMarketPrice()));
            //售价
            productDetailBean.setSellingPrice(product.getSettingPrice());
        } else {
            GoldPriceRecordBean goldPriceRecordBean = goldPriceRecordService.findLastByTime();
            if (goldPriceRecordBean != null) {
                //金价类型设置(1:实时金价 )   市场价格= 实时金价 + 产品参数设置的值
                productDetailBean.setMarketPrice(productDetailBean.getMarketPrice());
                //售价
                productDetailBean.setSellingPrice(goldPriceRecordBean.getLatestpri());
            }
        }

        //获取产品标签信息
        if (product.getType() == ProductTypeEnum.ENTITY.getType()) {
            List<LabelBean> labelList = new ArrayList<>();
            for (String labelId : product.getLabel().split(",")) {
                SerializeObject serializeObject = labelService.findLabelById(Integer.valueOf(labelId));
                if (serializeObject != null && serializeObject.getCode() == 200) {
                    LabelBean labelBean = JSON.parseObject(JSON.toJSONString(serializeObject.getData()), LabelBean.class);
                    labelList.add(labelBean);
                }
            }
            productDetailBean.setLabelList(labelList);

            //获取加工费信息
            SerializeObject serializeObject = processTemplateService.find(product.getProcessId());
            if (serializeObject != null && serializeObject.getCode() == 200) {
                JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(serializeObject.getData()));
                BigDecimal processCost = jsonObject.getBigDecimal("processCost");
                int disCount = jsonObject.getInteger("disCount");
                BigDecimal cost = processCost.multiply(new BigDecimal(disCount)).divide(new BigDecimal(100));
                productDetailBean.setProcessingFee(cost.setScale(4, BigDecimal.ROUND_HALF_UP));
            }
        }

        if (product.getType() == ProductTypeEnum.SMOOTH_GOLD.getType()) {
            List<ProductPublicityBean> productPublicityBeans = productPublicityMapper.findList(id);
            productDetailBean.setProductPublicityBeans(productPublicityBeans);
        }
        if (product.getType() == ProductTypeEnum.DISCOUNT_GOLD.getType()) {
            ProductDiscountSettings productDiscountSettings = productDiscountSettingsMapper.selectByProductId(id);
            if (!Objects.isNull(productDiscountSettings)) {
                productDetailBean.setMaxDiscountNum(productDiscountSettings.getMaxNum());
            }
        }

        List<ProductLeaseInfoBean> productLeaseInfoBeanList = productLeaseInfoService.findList(id);
        if (!CollectionUtils.isEmpty(productLeaseInfoBeanList)) {
            List<LeaseDay> leaseDayList = new ArrayList<>();
            for (ProductLeaseInfoBean productLeaseInfoBean : productLeaseInfoBeanList) {
                LeaseDay leaseDay = new LeaseDay();
                BeanUtils.copyProperties(productLeaseInfoBean, leaseDay);
                leaseDayList.add(leaseDay);
            }
            productDetailBean.setLeaseDayList(leaseDayList);
        }
        return productDetailBean;
    }

    @Override
    public int findIsBuy(String productId) {
        Ensure.that(productId).isNull("00000002");
        //查看是否开启交易
        Product product = productMapper.findById(productId);
        Ensure.that(product.getIsOpen() == TradeStatus.IsTrade.NO_TRADE).isTrue("15000029");
        return buySellCommon(productId, 1);
    }

    @Override
    public int findIsSell() {
        //获取活期id
        Product product = productMapper.findCurrentProduct();
        Ensure.that(product == null).isTrue("15000030");
        Ensure.that(product.getIsOpen() == TradeStatus.IsTrade.NO_TRADE).isTrue("15000029");
        return buySellCommon(product.getId(), 2);
    }

    @Override
    public int addToRaiseGram(String productId, BigDecimal gram) {
        Ensure.that(productId).isNull("00000002");
        Ensure.that(gram).isNull("00000002");
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("id", productId);
        param.put("gram", gram);
        return productMapper.addToRaiseGram(param);
    }

    @Override
    public List<ProductManageBean> listOverdueProduct() {
        return productMapper.queryOverdueProductList();
    }

    @Override
    public ProductFindBean findActivityTaskProduct() {
        Product product = productMapper.findActivityTaskProduct();
        Ensure.that(product == null).isTrue("00000003");
        ProductFindBean findBean = dozerBeanMapper.map(product, ProductFindBean.class);
        return findBean;
    }

    @Override
    public int updateStock(String productId, Integer stock) {
        Product product = productMapper.findById(productId);
        Ensure.that(product == null).isTrue("00000003");
        Map<String, Object> param = new HashMap<String, Object>();

        //库存修改变大时同时修改募集克重
        if (product.getStock().intValue() < stock.intValue()) {
            param.put("raiseGram", stock.intValue() * product.getSpecification().intValue());
        }
        param.put("id", productId);
        param.put("stock", stock);
        return productMapper.updateStock(param);
    }


    @Override
    public Map<String, Object> findProtocol(String productId, Integer type) {
        Map<String, Object> resultMap = new HashMap<>();
        Product product = productMapper.findById(productId);
        Ensure.that(product == null).isTrue("00000003");
        String protocolId = null;
        if (type == 1) {
            protocolId = product.getProtocolId();
        }

        if (type == 2) {
            protocolId = product.getLeaseProtocolId();
        }

        SerializeObject<ArticleBean> o = articleService.find("", protocolId);
        if (o.getCode() == ResultType.NORMAL) {
            ArticleBean articleBean = o.getData();
            resultMap.put("protocolId", protocolId);
            resultMap.put("protocolName", articleBean.getTitle());
            resultMap.put("content", articleBean.getContent());
            resultMap.put("productId", productId);
        }
        return resultMap;
    }


    @Override
    public List<ProductBean> findActivityProductList() {
        List<Product> productList = productMapper.findActivityProductList();
        List<ProductBean> productBeanList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(productList)) {
            for (Product product : productList) {
                ProductBean productBean = new ProductBean();
                BeanUtils.copyProperties(product, productBean);
                productBeanList.add(productBean);
            }
        }
        return productBeanList;
    }

    /**
     * 买卖公共方法
     *
     * @param productId
     * @param type
     * @return
     */
    public Integer buySellCommon(String productId, Integer type) {
        //查看符合时间段
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("day", LocalDate.now().toString());
        param.put("productId", productId);
        param.put("type", type);
        ProductTradeTime productTradeTime = productTradeTimeMapper.findByDay(param);
        Ensure.that(productTradeTime == null).isTrue("15000029");

        boolean flag = false;
        List<TradeTemplateTimeBean> list = tradeTemplateTimeMapper.findList(productTradeTime.getTemplateId());
        Ensure.that(list == null || list.isEmpty()).isTrue("15000029");  //如果不存在显示系统操作
        for (TradeTemplateTimeBean entity : list) {
            String startTimeSuffix = entity.getStartTime();
            String endTimeSuffix = entity.getEndTime();
            flag = getIsAccord(startTimeSuffix, endTimeSuffix);
            if (flag) return 0;
        }
        //如果都不符合条件--那么无法交易
        Ensure.that(flag).isFalse("15000029");
        return 0;
    }

    /**
     * 获取产品停售时间------目前定义：无募集期限为10年有效时间
     *
     * @param upTime 上线时间
     * @param day    募集天数
     * @return
     */
    public static LocalDateTime getStopTime(String upTime, int day) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonConstants.FORMAT);
        LocalDateTime currentTime = LocalDateTime.parse(upTime, df);
        String date = null;
        if ("0".equals(day)) {
            currentTime = currentTime.plusYears(10);
        } else {
            currentTime = currentTime.plusDays(day);
        }
        return currentTime;
    }

    /**
     * 做废产品
     */
    public void cancelProduct(String id) {
        if (StringUtil.isNotEmpty(id)) {
            Map<String, Object> param = new HashMap<>();
            param.put("id", id);
            param.put("status", CommonConstants.ProductStatus.CANCEL.getIndex());
            productMapper.updateByPrimaryKeySelective(param);
        }
    }

    /**
     * 拼接逗号处理
     *
     * @param str
     * @return
     */
    public static String handle(String str) {
        if (StringUtils.isNotBlank(str)) {
            String result = str;
            String topStr = result.substring(0, 1);
            String lastStr = result.substring(result.length() - 1, result.length());
            if (topStr.contains(",")) {
                result = result.substring(1, result.length());
            }
            if (lastStr.contains(",")) {
                result = result.substring(0, result.length() - 1);
            }
            return result;
        }
        return null;
    }

    public boolean getIsAccord(String startTimeSuffix, String endTimeSuffix) {
        LocalDate today = LocalDate.now();
        String startTimeString = today + " " + startTimeSuffix + "";
        String endTimeString = today + " " + endTimeSuffix;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime startTime = LocalDateTime.parse(startTimeString, df);
        LocalDateTime endTime = LocalDateTime.parse(endTimeString, df);
        LocalDateTime currentTime = LocalDateTime.now();
        if (currentTime.compareTo(startTime) > 0 && currentTime.compareTo(endTime) < 0) return true;
        return false;
    }


    private void checkDiscountParams(ProductBean entityBean) {
        Ensure.that(entityBean.getMarketPrice().compareTo(new BigDecimal(60)) > 0).isTrue("15000075");
        Ensure.that(entityBean.getEffectiveDay()).isNull("15000005");
        Ensure.that(entityBean.getLeaseDayList() == null || entityBean.getLeaseDayList().isEmpty()).isTrue("15000061");

        Ensure.that(entityBean.getDiscountBean() == null).isTrue("15000070");
        ProductDiscountBean productDiscountBean = entityBean.getDiscountBean();
        //新用户初始次数默认为1
        if (productDiscountBean.getNewMemberNum() == null) {
            productDiscountBean.setNewMemberNum(1);
        }

        //老用户初始次数默认为0
        if (productDiscountBean.getOldMemberNum() == null) {
            productDiscountBean.setOldMemberNum(0);
        }

        //邀请用户数默认为6
        if (productDiscountBean.getRatio() == null) {
            productDiscountBean.setRatio(6);
        }

        Ensure.that(productDiscountBean.getMaxNum() == null || productDiscountBean.getMaxNum() < 0
                || productDiscountBean.getMaxNum() > 10).isTrue("15000071");

        Ensure.that(productDiscountBean.getRatio() > 30).isTrue("15000072");

        /**
         * 产品详情集合
         */
        Ensure.that(entityBean.getProductInfoList() == null || entityBean.getProductInfoList().isEmpty()).isTrue("15000040");
        entityBean.getProductInfoList().stream().forEach(productInfoBean -> {
            Ensure.that(CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())).isTrue("15000048");
            Ensure.that(StringUtils.isBlank(productInfoBean.getTitle())).isTrue("15000047");
            Ensure.that(productInfoBean.getProductIntroduceList().size() < 1).isTrue("15000043");
            Ensure.that(productInfoBean.getProductIntroduceList().size() > 10).isTrue("15000041");
        });


        SerializeObject serializeObject = rateSettingsService.get(RateKeyEnum.ENTITY_GOLD.getKey());
        if (serializeObject != null && serializeObject.getData() != null) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(serializeObject.getData());
            EntityGoldBean entityGoldBean = JSONObject.toJavaObject(jsonObject, EntityGoldBean.class);
            entityBean.setLeaseCloseType(entityGoldBean.getLeaseCloseType());
            entityBean.setLeaseCalculateGoldType(entityGoldBean.getLeaseCalculateGoldType());
            entityBean.setLeaseCalculateGoldTime(entityGoldBean.getLeaseCalculateGoldTime());
        }
        entityBean.setGramMin(new BigDecimal(entityBean.getSpecification()));
        entityBean.setGramMax(new BigDecimal(entityBean.getSpecification()));
        //设置库存克重
        entityBean.setRaiseGram(new BigDecimal(entityBean.getStock().intValue() * entityBean.getSpecification().intValue()));
        //设置默认值
        entityBean.setYearsIncome(BigDecimal.ZERO);

        entityBean.setInvestDay("0");
        if (StringUtils.isBlank(entityBean.getPriceMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getPriceMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        entityBean.setAwardSetting(0);
        entityBean.setBuyAwardSetting(0);
        entityBean.setUserAstrictStatus(0);
    }

    /**
     * 安稳金参数校验
     *
     * @param entityBean
     */
    private void checkSmoothParams(ProductBean entityBean) {
        Ensure.that(entityBean.getCanBuyUserType()).isNull("15000056");
        Ensure.that(entityBean.getEffectiveDay()).isNull("15000005");
        Ensure.that(entityBean.getInterestAccrualType()).isNull("15000008");
        Ensure.that(entityBean.getLeaseProtocolId()).isNull("15000023");
        Ensure.that(entityBean.getUserAstrictStatus()).isNull("15000055");
        Ensure.that(entityBean.getStock()).isNull("15000057");
        Ensure.that(entityBean.getUserAstrictStatus() == 1 &&
                (entityBean.getUserAstrictNum() == null || entityBean.getUserAstrictNum() == 0)).isTrue("15000045");
        Ensure.that(entityBean.getUserAstrictStatus() == 2 &&
                (entityBean.getUserAstrictGram() == null || entityBean.getUserAstrictGram() == 0)).isTrue("15000049");
        Ensure.that(entityBean.getLeaseDayList() == null || entityBean.getLeaseDayList().isEmpty()).isTrue("15000061");

        /**
         * 产品详情集合
         */
        Ensure.that(entityBean.getProductInfoList() == null || entityBean.getProductInfoList().isEmpty()).isTrue("15000040");
        //Ensure.that(entityBean.getProductInfoList().size() < 1).isTrue("15000042");
        //Ensure.that(entityBean.getProductInfoList().size() > 6).isTrue("15000041");
        entityBean.getProductInfoList().stream().forEach(productInfoBean -> {
            Ensure.that(CollectionUtils.isEmpty(productInfoBean.getProductIntroduceList())).isTrue("15000048");
            Ensure.that(StringUtils.isBlank(productInfoBean.getTitle())).isTrue("15000047");
            Ensure.that(productInfoBean.getProductIntroduceList().size() < 1).isTrue("15000043");
            Ensure.that(productInfoBean.getProductIntroduceList().size() > 10).isTrue("15000041");
        });

        /**
         * 产品宣传图片
         */
        if (!CollectionUtils.isEmpty(entityBean.getProductPublicityBeans())) {
            Ensure.that(entityBean.getProductPublicityBeans().size() > 5).isTrue("15000064");
            entityBean.getProductPublicityBeans().stream().forEach(productPublicityBean -> {
                Ensure.that(StringUtils.isBlank(productPublicityBean.getTitle())).isTrue("15000065");
                Ensure.that(StringUtils.isBlank(productPublicityBean.getContent())).isTrue("15000066");
                Ensure.that(StringUtils.isBlank(productPublicityBean.getImgUrl())).isTrue("15000067");
                Ensure.that(productPublicityBean.getTitle().length() > 15).isTrue("15000068");
                Ensure.that(productPublicityBean.getContent().length() > 300).isTrue("15000069");
            });
        }

        SerializeObject serializeObject = rateSettingsService.get(RateKeyEnum.ENTITY_GOLD.getKey());
        if (serializeObject != null && serializeObject.getData() != null) {
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(serializeObject.getData());
            EntityGoldBean entityGoldBean = JSONObject.toJavaObject(jsonObject, EntityGoldBean.class);
            entityBean.setLeaseCloseType(entityGoldBean.getLeaseCloseType());
            entityBean.setLeaseCalculateGoldType(entityGoldBean.getLeaseCalculateGoldType());
            entityBean.setLeaseCalculateGoldTime(entityGoldBean.getLeaseCalculateGoldTime());
        }

        //设置最低的购买克重
        entityBean.setGramMin(new BigDecimal(entityBean.getSpecification()));
        //设置库存克重
        entityBean.setRaiseGram(new BigDecimal(entityBean.getStock().intValue() * entityBean.getSpecification().intValue()));
        //设置默认值
        entityBean.setYearsIncome(BigDecimal.ZERO);

        /*********************************结束***********************************************/
        //设置开始计息日期 T+1
        entityBean.setInterestAccrualDay(1);
        entityBean.setInvestDay("0");
        if (StringUtils.isBlank(entityBean.getPriceMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getPriceMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMin() + "")) {
            entityBean.setPriceMin(BigDecimal.ZERO);
        }
        if (StringUtils.isBlank(entityBean.getGramMax() + "")) {
            entityBean.setPriceMax(BigDecimal.ZERO);
        }
    }

    public static void main(String[] args) {
       /* System.out.println(NumberUtils.isCreatable("1.5x"));
        DateTimeFormatter df = DateTimeFormatter.ofPattern(CommonConstants.FORMAT);
        LocalDateTime currentTime = LocalDateTime.parse("2018-01-29 01:00:00",df);
        currentTime = currentTime.plusDays(1);
        System.out.println(currentTime);*/

        /*System.out.println(handle("1,2,"));*/
       /* LocalDate today = LocalDate.now();
        String startTime = "09:00";
        String endTime = "21:00";
        String s1 = today+" "+startTime;
        String s2 = today+" " +endTime;
        System.out.println(s1);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        LocalDateTime ldt1 = LocalDateTime.parse(s1,df);
        LocalDateTime ldt2 = LocalDateTime.parse(s2, df);
        LocalDateTime currentTime = LocalDateTime.now();
        System.out.println(currentTime.compareTo(ldt1) > 0);
        System.out.println(currentTime.compareTo(ldt2));*/
       /* BigDecimal dt = new BigDecimal("1");
        BigDecimal dt1 = new BigDecimal("3");
        BigDecimal dt2 = dt.divide(dt1, 4, BigDecimal.ROUND_HALF_UP);
        System.out.println("----除法(保留四位小数)---"+dt2);
        System.out.println("----乘法(保留二位小数)---"+dt2.multiply(BigDecimal.valueOf(100l)).setScale(2));*/
        BigDecimal dt = new BigDecimal("0");
        BigDecimal dt1 = new BigDecimal("0");
        System.out.println(dt.subtract(dt1));
        System.out.println(UF.getRandomUUID());
    }
}
